package com.draemoncode.weixindb.action;

import com.draemoncode.weixindb.constant.MessagePackageTypeConstant;
import com.draemoncode.weixindb.constant.PodFlagConstant;
import com.draemoncode.weixindb.constant.TingZhiXiaZhuConstant;
import com.draemoncode.weixindb.domain.B_Pod;
import com.draemoncode.weixindb.domain.B_XiaZhu;
import com.draemoncode.weixindb.mvc.exception.BusiException;
import com.draemoncode.weixindb.repository.B_PodRepository;
import com.draemoncode.weixindb.repository.B_XiaZhuRepository;
import com.draemoncode.weixindb.server.CMessagePackage;
import com.draemoncode.weixindb.server.IAction;
import com.draemoncode.weixindb.util.ValueUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author yangz
 * @date 2017/4/9
 *
 */
@Component
public class TingZhiXiaZhuPodAction implements IAction<B_Pod, Object>{

    public final static String ACTION = "tingzhixiazhu";

    @Autowired
    private B_PodRepository b_podRepository;

    @Autowired
    private B_XiaZhuRepository b_xiaZhuRepository;

    @Override
    public Boolean shoudProcess(String action) {
        return ACTION.equals(action);
    }

    @Override
    public B_Pod busiExec() {
        B_Pod pod = b_podRepository.findByFlag(PodFlagConstant.ING);
        if(pod == null){
            throw new BusiException(HttpStatus.BAD_REQUEST.value(), "没人上庄");
        }
        return pod;
    }

    @Override
    public Object uiExec(B_Pod busiResult) {
        return null;
    }

    @Override
    public CMessagePackage buildResponse(B_Pod busiResult, Object uiResult) {
        Map<String, Object> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        sb.append("-------本局下注-------\n");
        List<B_XiaZhu> byPod_id = b_xiaZhuRepository.findByPod_id(busiResult.getId());
        for (B_XiaZhu b_xiaZhu : byPod_id) {
            sb.append("[ " + b_xiaZhu.getMember_name() + " ]").append(" : ").append(ValueUtil.formatMoney(b_xiaZhu.getXia_zhu())).append("\n");
        }
        CMessagePackage response = new CMessagePackage(MessagePackageTypeConstant.RESPONSE_TING_ZHI_XIA_ZHU);
        map.put(TingZhiXiaZhuConstant.RESPONSE_SHOW_CONTENT, sb.toString());
        response.setSyncid(busiResult.getId());
        response.setMsg(map);
        return response;
    }
}
